package com.uroad.lib.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.uroad.lib.R;
import com.uroad.lib.data.Constant;
import com.uroad.lib.http.OkHttpUtils;
import com.uroad.lib.http.builder.PostFormBuilder;
import com.uroad.lib.http.callback.StringCallback;
import com.uroad.lib.util.activity.ActivityUtil;
import com.uroad.lib.util.net.NetWorkUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public abstract class BaseFragment extends Fragment {

    private FrameLayout flBaseContent, flBaseLoad;
    private LinearLayout llBaseRefresh;
    private ImageView ivBaseLoad;
    private TextView tvBaseLoad, tvBaseRefresh, tvBaseBack;
    public View view;
    private boolean showNoNetPage = false;
    private boolean showErrorPage = false;
    private boolean showNoNetToast = true;
    private boolean showErrorToast = true;
    private Context mContext;

    private void assignViews() {
        view = LayoutInflater.from(getActivity()).inflate(
                R.layout.fragment_base_fragment, null);
        flBaseContent = (FrameLayout) view.findViewById(R.id.flBaseContent);
        flBaseLoad = (FrameLayout) view.findViewById(R.id.flBaseLoad);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        assignViews();
        addBaseLoadView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return view;
    }

    @Override
    public void onDestroyView() {
        try {
            ViewGroup viewp = (ViewGroup) view.getParent();
            viewp.removeView(view);
        } catch (Exception e) {
        }
        super.onDestroyView();
    }

    /**
     * 网络请求
     *
     * @param methodUrl url方法名eg."/sys/getFileVer"
     * @param params    请求参数
     * @param id
     */
    public void doRequest(String methodUrl, HashMap<String, Object> params, String id) {
        if ("WIFI".equals(Constant.NET)){
            doPost(Constant.BASE_URL + methodUrl, params, id);
        }else if("4G".equals(Constant.NET)){
            doPost(Constant.BASE_URL_4G + methodUrl, params, id);
        }
    }

    /***
     * 网络请求
     *
     * @param methodUrl url 完整的URL请求
     * @param params    请求参数
     * @param id
     */
    public void doAllUrlRequest(String methodUrl, HashMap<String, Object> params, String id) {
        doPost(methodUrl, params, id);
    }

    public void doPost(String url, HashMap<String, Object> params, String id) {
        if(mContext == null){
            mContext = getContext();
        }
        if (!NetWorkUtil.checkNet(mContext)) {
            OnHttpNetWork(id);
            return;
        }
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                postFormBuilder.addParams(entry.getKey(), (String) entry.getValue());
            }
        }
        postFormBuilder.url(url)
                .id(id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, String id) {
                        OnHttpFailure(id);
                    }

                    @Override
                    public void onResponse(String response, String id) {
                        try {
                            OnHttpTaskComplete(response, id);
                        } catch (Exception e) {
                            OnHttpFailure(id);
                        }
                    }
                });
    }


    protected void showLongToast(String pMsg) {
        if (!TextUtils.isEmpty(pMsg))
            DialogHelper.showShortTost(getActivity(), pMsg);
    }

    protected void showShortToast(String pMsg) {
        if (!TextUtils.isEmpty(pMsg))
            DialogHelper.showShortTost(getActivity(), pMsg);
    }

    public View setBaseContentLayout(int layoutResId) {
        flBaseContent.removeAllViews();
        LayoutInflater inflater = (LayoutInflater) getActivity()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(layoutResId, null);
        flBaseContent.addView(v);
        return view;
    }

    public View setBaseContentLayout(View v) {
        flBaseContent.removeAllViews();
        flBaseContent.addView(v);
        return view;
    }

    protected void openActivity(Class<?> pClass) {
        ActivityUtil.openActivity(getActivity(), pClass);
    }

    protected void openActivity(Class<?> pClass, Bundle pBundle) {
        ActivityUtil.openActivity(getActivity(), pClass, pBundle);
    }

    protected void openHistoryActivity(Class<?> pClass) {
        ActivityUtil.openActivityFromHistory(getActivity(), pClass);
    }

    protected void openActivity(String pAction, Bundle pBundle) {
        ActivityUtil.openActivity(getActivity(), pAction, pBundle);
    }

    protected void addBaseLoadView() {
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.view_baseload, null);
        flBaseLoad.addView(view);
        ivBaseLoad = (ImageView) view.findViewById(R.id.ivBaseLoad);
        tvBaseLoad = (TextView) view.findViewById(R.id.tvBaseLoad);
        llBaseRefresh = (LinearLayout) view.findViewById(R.id.llBaseRefresh);
        tvBaseRefresh = (TextView) view.findViewById(R.id.tvBaseRefresh);
        tvBaseBack = (TextView) view.findViewById(R.id.tvBaseBack);

        flBaseLoad.setOnClickListener(onClickListener);
        ivBaseLoad.setOnClickListener(onClickListener);
        tvBaseRefresh.setOnClickListener(onClickListener);
        tvBaseBack.setOnClickListener(onClickListener);
    }

    /**
     * 设置加载、无网络、接口调用失败的信息
     *
     * @param res  显示的图片
     * @param text 正在加载的文字
     */
    public void setPagePic(int res, String text) {
        flBaseLoad.setVisibility(View.VISIBLE);
        ivBaseLoad.setImageResource(res);
        if (!TextUtils.isEmpty(text)) {
            tvBaseLoad.setVisibility(View.VISIBLE);
            tvBaseLoad.setText(text);
        } else {
            tvBaseLoad.setVisibility(View.GONE);
        }
    }

    /**
     * 默认加载页面
     **/
    protected void setPageLoading() {
        setPagePic(R.drawable.ic_base_loading, "正在加载...");
        llBaseRefresh.setVisibility(View.GONE);
    }

    protected void setPageEndLoading() {
        flBaseLoad.setVisibility(View.GONE);
    }

    protected void setPageNetworkError() {
        setPagePic(R.drawable.ic_base_no_net, "");
        llBaseRefresh.setVisibility(View.GONE);
    }

    protected void setPageLoadNodata() {
        setPagePic(R.drawable.ic_base_error, "");
        llBaseRefresh.setVisibility(View.VISIBLE);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int i = view.getId();
            if (i == R.id.ivBaseLoad) {
                if (tvBaseLoad.getVisibility() == View.GONE && llBaseRefresh.getVisibility() == View.GONE) {
                    onBaseRefresh(view);
                }
            } else if (i == R.id.tvBaseRefresh) {
                onBaseRefresh(view);
            } else if (i == R.id.tvBaseBack) {
                onBaseBack(view);
            }
        }
    };

    protected void onBaseRefresh(View v) {
    }

    protected void onBaseBack(View v) {

    }

    /**
     * 设置是否显示接口超时或错误的提示页面
     *
     * @param showErrorPage
     */
    public void setShowErrorPage(boolean showErrorPage) {
        this.showErrorPage = showErrorPage;
    }

    /**
     * 设置是否显示无网络的提示页面
     *
     * @param showNoNetPage
     */
    public void setShowNoNetPage(boolean showNoNetPage) {
        this.showNoNetPage = showNoNetPage;
    }

    /**
     * 设置是否显示接口超时的Toast提示
     *
     * @param showErrorToast
     */
    public void setShowErrorToast(boolean showErrorToast) {
        this.showErrorToast = showErrorToast;
    }

    /**
     * 设置是否显示无网络的Toast提示
     *
     * @param showNoNetToast
     */
    public void setShowNoNetToast(boolean showNoNetToast) {
        this.showNoNetToast = showNoNetToast;
    }

    /**
     * 没有网络回调
     *
     * @param msg
     */
    public void OnHttpNetWork(String msg) {
        if (showNoNetPage) {
            setPageNetworkError();
        }
        if (showNoNetToast) {
            showShortToast("网络异常，请检查网络");
        }
    }

    /**
     * 请求数据失败回调
     *
     * @param msg
     */
    public void OnHttpFailure(String msg) {
        if (showErrorPage) {
            setPageLoadNodata();
        }
//        if (showErrorToast) {
//            showShortToast("系统繁忙，请稍后再试");
//        }
    }

    /**
     * 请求数据完成回调
     *
     * @param result 返回数据
     * @param id     返回数据类型
     */
    public void OnHttpTaskComplete(String result, String id) {

    }
}
